//
//  WPWBStatusViewModel.swift
//  WB
//
//  Created by 汪鹏 on 2016/12/25.
//  Copyright © 2016年 汪鹏. All rights reserved.
//  微博数据的视图模型

import Foundation
import SDWebImage

/// 微博视图模型
/// 实现字典转模型
/// 实现上拉／下拉
class WPWBViewModel {
    
    /// 懒加载存放微博视图的数组
    lazy var status:[WPSingleWBViewModel] = [WPSingleWBViewModel]()
    
    /// 加载微博数据
    ///
    /// - Parameters:
    ///   - isPullUp: 标记是上拉加载
    ///   - completation: 完成的回调
    func loadWbStatus(isPullUp: Bool, completation:@escaping (_ isSuccess: Bool, _ hasMorePullup: Bool) -> ()) {
        
        let since_id = isPullUp ? 0 : status.first?.statu.id ?? 0
        
        let max_id = !isPullUp ? 0 : status.last?.statu.id ?? 0
        
        WPNetManager.shareManager.statusList(since_id: since_id, max_id: max_id) { (json, isSuccess) in
            
            if !isSuccess { // 请求失败，直接返回
                
                completation(isSuccess,false)
                
                return
                
            }
            
            var statusArray = [WPSingleWBViewModel]() // 临时数组
            
            // 遍历json数组，一次转模型
            for dict in json ?? [] {
                
                guard let model = WPWBStatus.yy_model(with: dict) else{
                    
                    continue
                }
                
                statusArray.append(WPSingleWBViewModel(model: model))
            }
            
            /*
            // 字典转模型
            guard let statusArray = NSArray.yy_modelArray(with: WPWBStatus.self, json: json ?? []) as? [WPWBStatus] else{
                
                print(#function+"数组为空，微博数据字典转模型失败！")
                
                completation(isSuccess,false)
                
                return
            }
            */
            
            //print(statusArray)
            
            // 拼接数据
            if isPullUp == true { // 如果是上拉加载
                
                self.status += statusArray
                
            }else{ // 如果是下拉刷新
                
                self.status = statusArray + self.status
            }
            
            // 完成的回调
            if statusArray.count > 0 { // 有数据返回
                
                print(#function+"获取微博数据成功")
                
                // 开始缓存单张图片
                self.cacheSingleImage(SingleWBViewModels: statusArray,completation: completation)
                
                //completation(isSuccess,true)
                
            }else{
                
                print(#function+"获取微博数据失败")
                    
                completation(isSuccess,false)
            }
            
        }
    
    }
    /// 缓存单张图片
    ///
    /// - Parameter SingleWBViewModels:[WPSingleWBViewModel]
    private func cacheSingleImage(SingleWBViewModels:[WPSingleWBViewModel], completation: @escaping (_ isSuccess: Bool, _ hasMorePullup: Bool) -> ()) {
        
        // 实例组对象
        let group = DispatchGroup()
        
        // 记录下载的图片大小
        var length = 0
        
        // 遍历此次下载的单张视图模型数组
        for SingleWBViewModel in SingleWBViewModels {
            
            if SingleWBViewModel.pic_urls?.count != 1 { // 不是一张图就结束此次循环
                
                continue
            }
            
            guard let img_String = SingleWBViewModel.pic_urls?[0].thumbnail_pic,
            
                let img_url = URL(string:img_String)else{
                
                continue
            }
            
            // 入组
            group.enter()
            
            // 开始缓存图片
            SDWebImageManager.shared().downloadImage(with: img_url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    
                    // 更新配图视图大小
                    SingleWBViewModel.updatePictureSize(image: image)
                }
               
                // 出组
                group.leave()
            })
        }
        
        // 监听调度组
        group.notify(queue: DispatchQueue.main) { 
            
            // 回调刷新
            completation(true,true)
            
        }
        
    }
}
